import { Component, Vue, Watch, Ref } from 'vue-property-decorator'
import { RootState } from '@/store'
import { Action, Mutation, State } from 'vuex-class'
import styles from './ApplyPage.less'
import applyStyle from '../NewApply/ApplyDetail.less'
import PrintDialog from './PrintDialog'
import Upload from '@/components/Upload'
import { ISealData } from '@/store'
import {
  IStatus,
  adminTypes,
  userLicenseTypes,
  useTypes,
  orgTypes,
  orgLicenseTypes,
  sealTypes,
  sealUseTimeList,
  payTypes,
} from '@/lib/sealFormat'
import { ElForm } from 'element-ui/types/form'
import { ElFormItem } from 'element-ui/types/form-item'
import OptionLine from '@/components/OptionLine'
import { UserState } from '@/store/modules/user'
import { desensitization } from '@/lib/utils'
import { getTimeline, formatStatus } from '@/lib/sealFormat'
import ImagePreview from '@/components/ImagePreview'
import SelectTree from '@/components/SelectTree'
import SelectTreeEmpty from '../../modules/selectTreeEmpty'
import DetailItem from '@/components/DetailItem'
import PdfViewDialog from '@/components/pdfViewDialog'
import ApplyLicenseNumber from './ApplyLicenseNumber'
import RadioGroup from './radioGroup/RadioGroup'
import PaymentOrder from './PaymentOrder'
import Steps from '@/components/Steps'
import PreviewImages from '@/components/previewImages'
import SelectDialog from '@/components/selectDialog'
import html2canvas from 'html2canvas'
import { Route } from 'vue-router'
import { ICardOption } from '../../components/selectDialog/selectCard'
import HandWriteQrCode from './handWriteQrCode'
import { pollRequest } from '@/lib/utils'
Component.registerHooks(['beforeRouteLeave'])
const fileTypes = [
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/bmp',
  'image/gif',
]
const fileSizeLimit = 10
const newApplyFileSizeLimit = 30
const sealData: ISealData = {
  agentId: '',
  agentLicenseNumber: '',
  agentLicenseType: undefined,
  agentName: '',
  agentMobile: '',
  organizeAdministrationLevel: undefined,
  organizeLicenseNumber: '',
  organizeLicenseType: undefined,
  organizeName: '',
  organizeType: undefined,
  organizeUUID: '',
  useType: null,
  sealType: null,
  sealName: '',
  auditOrganizeName: '',
  auditOrganizeLicenseType: undefined,
  auditOrganizeLicenseNumber: '',
  auditOrganizeUUID: '',
  fileKey: '',
  url: '',
  agentMobileDes: '',
  agentLicenseNumberDes: '',
  area: '',
  reasonType: 3,
  reason: '',
  reasonContent: '',
  payType: 1,
  sealUseTime: 3,
  orderNo: '',
  licenseNumberSource: 1,
  licenseNumberFileKey: '',
  sealElectronicPicFileKey: '',
  sealElectronicPicSubmitType: null,
}

const reasonList: any[] = [
  { id: 1, value: '虚假注册' },
  { id: 2, value: '单位调整或注销' },
  { id: 3, value: '印章丢失' },
  { id: 4, value: '其他情况' },
]

const useTypeOptions: any = {
  1: {
    subValue: '需要硬件介质UKey盖章',
    img: require('@/assets/seal/ukey.png'),
    imgWidth: '26px',
    imgHeight: 'auto',
  },
  2: {
    subValue: '用于第三方系统调用（不含Ukey）',
    img: require('@/assets/seal/yun.png'),
    imgWidth: '26px',
    imgHeight: 'auto',
  },
}

const filterReasonValue = (id: number) => {
  return (reasonList.filter((item: any) => item.id === id)[0] || {}).value || ''
}

const filterReasonId = (value: string) => {
  return (
    (reasonList.filter((item: any) => item.value === value)[0] || {}).id || 4
  )
}

const formLabelWidth3: string = '48px'
const formLabelWidth4: string = '60px'
const formLabelWidth5: string = '84px'
// const formLabelWidth6: string = '96px'
// const formLabelWidth7: string = '120px'
const formLabelWidth8: string = '72px'
const detailData2 = [
  {
    title: '用章机构基本信息',
    child: [
      {
        key: 'organizeName',
        labelWidth: formLabelWidth3,
        label: '机构名称',
        content: '',
      },
      {
        key: 'organizeType',
        labelWidth: formLabelWidth8,
        label: '机构类型',
        content: '',
      },
      {
        key: 'organizeCardType',
        label: '证照类型',
        labelWidth: formLabelWidth3,
        content: '',
      },
      {
        key: 'organizeCardId',
        label: '证照号码',
        labelWidth: formLabelWidth8,
        content: '',
      },
      // { key: "organizeLevel", label: "行政等级", labelWidth: formLabelWidth3, content: "" }
    ],
  },
]

const lastDetail = [
  {
    title: '经办人基本信息',
    child: [
      {
        key: 'agentName',
        label: '经办人姓名',
        labelWidth: formLabelWidth4,
        content: '',
      },
      {
        key: 'agentMobileDes',
        label: '经办人手机号',
        labelWidth: formLabelWidth8,
        content: '',
      },
      {
        key: 'agentLicenseTypeName',
        label: '经办人证件类型',
        labelWidth: formLabelWidth5,
        content: '',
      },
      {
        key: 'agentLicenseNumberDes',
        label: '经办人证件号',
        labelWidth: formLabelWidth8,
        content: '',
      },
    ],
  },
]

const sealDetail = [
  {
    title: '印章信息',
    id: 3,
    child: [
      {
        key: 'sealType',
        label: '印章类别',
        content: '',
        labelWidth: formLabelWidth3,
        tips:
          '组织机构的电子法定名称章需要上级主管部门审批，其他专用章（包括经济合同章、财务专用章等）。在名称式样上应与单位正式印章有所区别，经本单位领导批准后可以申请。',
      },
      {
        key: 'sealName',
        label: '印章名称',
        labelWidth: formLabelWidth8,
        content: '',
      },
      {
        key: 'sealUseType',
        label: '用章方式',
        labelWidth: formLabelWidth3,
        content: '',
        tips:
          '选择Ukey签章需要硬件介质UKey盖章，选择云签章可用于开放服务使用API调用。',
      },
    ],
  },
]

const validateSealName = (rule: any, value: string, callback: any) => {
  if (/[!@#$%^&*!！@￥……]/gi.test(value)) {
    callback(new Error('印章名称不能包含特殊字符'))
  } else {
    callback()
  }
}

const wrongInfoOptions: ICardOption[] = [
  {
    icon: 'iconjigouxinxiyouwu',
    title: '机构信息有误',
    description: '机构名称或机构类型错误',
    titleDesc: '（需离开当前页面）',
  },
  {
    icon: 'iconzhengzhaoxinxiyouwu',
    title: '证照信息缺失或有误',
    description: '证照号码或证照类型缺失或有误',
    titleDesc: '（不会中断当前申请流程）',
  },
]

@Component({})
export default class ApplyPage extends Vue {
  @State((state: RootState) => state.applyPage.visible)
  private visible!: boolean

  @State((state: RootState) => state.user.ignoreUploadApplyExampleHint)
  private isExampleStopped!: boolean

  stopShowingExample: boolean = false
  private qrCodeImg!: string
  stop!: any
  handWriteSealUrl: string = ''
  private qrInvalid: boolean = false
  private handWritePreviewVisible: boolean = false
  // @State((state: RootState) => state.applyPage.applyLicenseNumberData)
  // private applyLicenseNumberData!: any;
  private active = 0
  private uploadUrl: string = '/seal/rest/file/uploadPicMulti'
  private saveLoading: boolean = false
  private organize!: any
  private sealOption: any[] = []

  private auditOrgs: any = []

  private successInterval: any
  private second = 0
  private applyId: any = ''
  private sealSn: any = ''
  private organizeName: string = ''
  private areas = []
  private defaultExpended: any = []
  private area = ''
  private showAreaError = false

  private options: any[] = []
  private areaOption: any[] = []
  private isShowUpdateOrganization: boolean = false

  private ApplyLicenseNumberData: any = {}
  private currentOrganizeUUID: string = ''

  private detailData: any[] = []
  private secondData: any[] = []
  private data: any = null
  private showOrderDialog: boolean = false
  private showOrderHelp: boolean = false
  private orderPayTypes: any[] = []
  private recommendName: string = ''
  private lastUser: any = {} // 印章名称校验重复时上一个使用者信息
  private wrongInfoDialogVisible: boolean = false
  private isUploadExample: boolean = false // 是否为上传前的参考示例窗口
  private exampleVisible: boolean = false // 参考示例

  get exampleUrl() {
    return this.isPersonHandWrite
      ? [
          {
            title: '申请表示例',
            url: require('@/assets/referenceForPerson.png'),
          },
        ]
      : [
          {
            title: '申请表示例',
            url: require('@/assets/reference.png'),
          },
          {
            title: '印模示例',
            url: require('@/assets/reference-img.png'),
          },
        ]
  }
  private showIndex: number = 1

  sealData: ISealData = {
    agentId: '',
    agentLicenseNumber: '',
    agentLicenseType: undefined,
    agentName: '',
    agentMobile: '',
    organizeAdministrationLevel: undefined,
    organizeLicenseNumber: '',
    organizeLicenseType: undefined,
    organizeName: '',
    organizeType: undefined,
    organizeUUID: '',
    useType: 0,
    sealType: 0,
    sealName: '',
    auditOrganizeName: '',
    auditOrganizeLicenseType: undefined,
    auditOrganizeLicenseNumber: '',
    auditOrganizeUUID: '',
    fileKey: '',
    url: '',
    agentMobileDes: '',
    agentLicenseNumberDes: '',
    reasonType: 3,
    reason: '',
    reasonContent: '',
    sealUseTime: 1,
    payType: 1,
    orderNo: '',
    licenseNumberSource: 1,
    licenseNumberFileKey: '',
    sealElectronicPicFileKey: '',
    sealElectronicPicSubmitType: 0,
  }

  private sealApplyStatus: number = 0

  private isPdf: boolean = false
  private pdfDialogVisible: boolean = false
  private pdfUrl: string = ''
  private errorPage: boolean = false

  private formLabelWidth1 = '50px'
  private formLabelWidth2 = '84px'
  private formLabelWidth3 = '72px'
  private formLabelWidth4 = '56px'
  private imgVisible = false
  private validImageError = false
  private loadTree = false
  private file: any = {
    status: 'init',
  }
  private orderInfo: any = {}

  private querySealApplyPayPreOrderInfo: any = []

  private cascaderProps = {
    value: 'uuid',
    label: 'fullName',
    children: 'subList',
  }
  // 印章名称编辑过 默认 false
  private editedSealName: boolean = false
  // 打印预览图层显示控制
  private previewImageShow: boolean = false
  // 打印预览申请表图
  private previewSealImgs: any = []
  // html2canvas图片
  private printLoadedCanvas: string = ''
  // 是否显示打印按钮
  private showPrintBtn: boolean = true

  private sealRules = {
    organizeName: [
      { required: true, message: '请输入机构名称进行搜索', trigger: 'change' },
    ],
    sealName: [
      {
        required: true,
        message: '请输入印章名称',
        trigger: ['blur', 'change'],
      },
      {
        max: 50,
        message: '印章名称长度不能超过50个字符',
        trigger: ['blur', 'change'],
      },
      { validator: validateSealName, trigger: 'blur' },
    ],
    auditOrganizeUUID: [
      { required: true, message: '请选择上级审批机构', trigger: 'change' },
    ],
    sealType: [
      { required: true, message: '请选择印章类别', trigger: 'change' },
    ],
    useType: [{ required: true, message: '请选择用章方式', trigger: 'change' }],
    organizeType: [
      { required: true, message: '机构类型为空', trigger: 'change' },
    ],
    organizeLicenseType: [
      { required: true, message: '证照类型为空', trigger: 'change' },
    ],
    organizeLicenseNumber: [
      { required: true, message: '证照号码为空', trigger: 'change' },
    ],
    organizeAdministrationLevel: [
      { required: true, message: '行政等级不能为空', trigger: 'change' },
    ],
    agentName: [
      { required: true, message: '经办人姓名为空', trigger: 'change' },
    ],
    agentMobileDes: [
      { required: true, message: '经办人手机号为空', trigger: 'change' },
    ],
    agentLicenseType: [
      { required: true, message: '经办人证件类型为空', trigger: 'change' },
    ],
    agentLicenseNumberDes: [
      { required: true, message: '经办人证件号为空', trigger: 'change' },
    ],
    auditOrganizeLicenseType: [
      { required: true, message: '证照类型为空', trigger: 'change' },
    ],
    auditOrganizeLicenseNumber: [
      { required: true, message: '证照号码为空', trigger: 'change' },
    ],
    reason: [
      { required: true, message: `原因不能为空`, trigger: 'change' },
      { max: 255, message: '不能超过255个字符', trigger: 'change' },
    ],
    orderNo: [
      { required: true, message: `请输入支付宝订单号最后8位`, trigger: 'blur' },
      {
        pattern: /^\d{8}$/,
        message: '订单号格式不正确',
        trigger: 'blur',
      },
    ],
    sealElectronicPicFileKey: [
      {
        required: true,
        message: '请绘制电子名章',
        trigger: 'change',
      },
    ],
    sealElectronicPicSubmitType: [
      { required: true, message: '请选择电子名章创建方式', trigger: 'change' },
    ],
  }
  private handWriteQrCodeVisible: boolean = false

  @Ref() private readonly orderSubmitRef!: PaymentOrder

  @State((state: RootState) => state.applyPage.printVisible)
  private printVisible!: boolean
  @State((state: RootState) => state.applyPage.type) private type!: string
  @State((state: RootState) => state.user) private user!: UserState
  @State((state: RootState) => state.applyPage.orgList) private orgList!: any[]
  @State((state: RootState) => state.applyPage.auditOrgList)
  private auditOrgList!: any[]
  @Mutation('applyPage/setStateData') private setStateData!: (data: any) => {}
  @Action('newApply/saveSeal') private saveSeal!: any
  @Action('newApply/saveAndSubmit') private saveAndSubmit!: any
  @Action('newApply/sealDetail') private applyDetail!: any
  @Action('newApply/sealApplyPicSubmit') private sealApplyPicSubmit!: any
  @Action('newApply/checkSealNameRepeat') private checkSealNameRepeat!: any
  @Action('applyPage/createOrder') private createOrder!: any
  @Action('applyPage/querySealApplyPayOrderInfo')
  private querySealApplyPayOrderInfo!: any
  @Action('applyPage/finishQRCodePayOrder') private finishQRCodePayOrder!: any
  @Action('applyPage/queryOrg') private queryOrg!: any
  @Action('applyPage/queryAuditOrg') private queryAuditOrg!: any
  @Action('applyPage/getAreas') private getAreas!: any
  @Action('applyPage/getInitTree') private getInitTree!: any
  @Action('applyPage/sealApplyUnifiedSubmit')
  private sealApplyUnifiedSubmit!: any
  @Action('appliedForMe/sealDetail') private sealDetail!: any

  @Action('revokeApply/saveSeal') private saveRevokeSeal!: any
  @Action('revokeApply/saveAndSubmit') private saveAndSubmitRevoke!: any
  @Action('lossApply/lossSealApply') private lossSealApply!: any
  @Action('reissueApply/reissueApply') private reissueApply!: any
  @Action('user/accountDataMasking') private accountDataMasking!: any
  @Action('applyPage/createElectronicSealTask') createElectronicSealTask!: any
  @Action('applyPage/queryElectronicSealPic') queryElectronicSealPic!: any
  @Action('user/ignoreUploadApplyExampleHint')
  ignoreUploadApplyExampleHint!: any
  @Action('user/info') userInfo!: any

  get handWriteSuccess() {
    return !!this.handWriteSealUrl
  }
  // 退回状态
  get isBackApply() {
    return this.sealApplyStatus === 90
  }
  get firstContent() {
    // 第一页
    return this.type === 'newApply' ? this.newApplyFirst : this.revokeApplyFirst
  }

  get secondContent() {
    // 第二页
    return this.type === 'newApply'
      ? this.newApplySecond
      : this.type === 'revokeApply'
      ? this.revokeApplySecond
      : this.lossApplySecond
  }

  get thirdContent() {
    // 第三页
    return this.type === 'newApply' ? this.newApplyThird : this.finishContent
  }

  paymentOrder() {
    return <PaymentOrder ref="orderSubmitRef" />
  }

  get payContent() {
    return this.payRender
  }

  get finishContent() {
    // 完成页
    return this.finishRender
  }

  get operations() {
    // 操作按钮
    return this.type === 'newApply'
      ? this.newApplyOperationsRender
      : this.detailData && this.detailData.length > 0
      ? this.revokeApplyOperations
      : ''
  }

  newApplyOperations(active: number): any[] {
    const nextBtnText =
      active === 1
        ? '去上传'
        : active === 2 && this.isBackApply
        ? '提交审核'
        : active === 3
        ? '前往支付'
        : '下一步'

    // 进入上传页面时
    if (this.active === 2 && this.file.url) {
      this.previewSealImgs = [this.file.url]
    }

    const printBtn = {
      name: '打印',
      type: 'primary',
      class: {
        'btn-primary': true,
        'btn-primary-hover': true,
        f14: true,
      },
      event: () => {
        // 打印
        this.print()
      },
      show: (act: any): boolean => [0, 1, 2, 3].indexOf(act) > -1,
    }
    const prevBtn = {
      name: '上一步',
      event: () => {
        this.active--
      },
      class: {
        f14: true,
      },
      show: (act: any): boolean => [1, 2, 3].indexOf(act) > -1,
    }
    const nextBtn = {
      name: nextBtnText,
      event: () => {
        this.next()
      },
      type: 'primary',
      class: {
        'btn-primary': true,
        'btn-primary-hover': active !== 2 || this.validField(),
        f14: true,
      },
      style: {
        marginLeft: active === 0 && '123px',
      },
      show: (act: any): boolean => [0, 1, 2, 3].indexOf(act) > -1,
    }
    const toUploadBtn = {
      name: '已盖章,去上传',
      event: () => {
        this.next()
      },
      type: 'primary',
      hoverTips: '请先打印《电子印章申请表》，加盖印模后即可上传',
      class: {
        'btn-primary': true,
        'btn-primary-hover': active !== 2 || this.validField(),
        f14: true,
      },
      style: {},
      show: (act: any): boolean => [0, 1, 2, 3].indexOf(act) > -1,
    }
    const actionConfig: any[] = this.errorPage
      ? []
      : active === 0
      ? [nextBtn]
      : active === 1
      ? [prevBtn, printBtn, toUploadBtn]
      : [prevBtn, nextBtn]

    // let actionConfig: any[] = active === 1
    return actionConfig.filter(item => {
      return item.show(active)
    })
  }

  get newApplyOperationsRender() {
    const btns = this.newApplyOperations(this.active)

    // 新领申请操作
    return this.active === 4 ? (
      ''
    ) : (
      <div class={styles.option}>
        <div class="new-apply-wrapper">
          {btns.map((item: any) => {
            if (item.hoverTips) {
              return (
                <el-tooltip placement="bottom-start">
                  <p slot="content">{item.hoverTips}</p>
                  <el-button
                    type={item.type}
                    class={item.class}
                    disabled={this.saveLoading}
                    style={item.style}
                    onClick={item.event}
                  >
                    {item.name}
                  </el-button>
                </el-tooltip>
              )
            }

            return (
              <el-button
                type={item.type}
                class={item.class}
                disabled={this.saveLoading}
                style={item.style}
                onClick={item.event}
              >
                {item.name}
              </el-button>
            )
          })}
          {/* {(this.active === 0 || this.active === 1) && (
						<el-button
							disabled={this.saveLoading}
							onClick={() => {
								this.back();
							}}
						>
							关闭
					</el-button>
					)}
					{this.active !== 0 && (
						<el-button
							disabled={this.saveLoading}
							onClick={() => {
								this.active--;
							}}
						>
							上一步
					</el-button>
					)}

            {this.active === 2 && (
              <el-button disabled={this.saveLoading} onClick={this.notSubmit}>
                暂不提交
					</el-button>
            )}
					<el-button
						type="primary"
						class={[{ "btn-primary": true, "btn-primary-hover": this.active !== 2 || this.validField() }]}
						disabled={this.saveLoading}
						onClick={() => {
							this.next();
						}}
					>
						{this.active === 2 ? "提交审核" : "下一步"}
					</el-button> */}
        </div>
      </div>
    )
  }

  get revokeApplyOperations() {
    return this.active === 2 ? (
      ''
    ) : (
      <div class={styles.option}>
        <div class="new-apply-wrapper">
          {this.active !== 0 && (
            <el-button
              disabled={this.saveLoading}
              onClick={() => {
                this.active--
              }}
            >
              上一步
            </el-button>
          )}
          {(this.active === 0 ||
            (this.type !== 'revokeApply' && this.active === 1)) && (
            <el-button
              disabled={this.saveLoading}
              onClick={() => {
                this.back()
              }}
            >
              关闭
            </el-button>
          )}
          {this.type === 'revokeApply' && this.active === 1 && (
            <el-button
              disabled={this.saveLoading}
              onClick={() => {
                this.nextRevoke(true)
              }}
            >
              暂不提交
            </el-button>
          )}
          <el-button
            type="primary"
            class={[
              {
                'btn-primary': true,
                'btn-primary-hover': this.active !== 2 || this.validField(),
              },
            ]}
            disabled={this.saveLoading}
            onClick={() => {
              this.nextRevoke(false)
            }}
          >
            {this.active === 1
              ? this.type === 'lossApply'
                ? '提交'
                : '提交审核'
              : '确认无误'}
          </el-button>
        </div>
      </div>
    )
  }

  get newApplyFirst() {
    // 新领申请第一步
    return (
      <div>
        <p class={styles.panel}>申请人基本信息</p>
        <el-row class="new-apply-wrapper" style="padding-left: 56px;">
          <el-col
            span={4}
            class="over-hidden mr5"
            title={this.sealData.agentName}
          >
            真实姓名：{this.sealData.agentName}
          </el-col>
          <el-col span={5}>手机号码：{this.sealData.agentMobileDes}</el-col>
          <el-col span={4}>
            证件类型：
            {formatStatus(userLicenseTypes, this.sealData.agentLicenseType)}
          </el-col>
          <el-col span={6}>
            证件号码：{this.sealData.agentLicenseNumberDes}
          </el-col>
        </el-row>
        <p class={styles.panel}>
          <span class={styles.required}>*</span>用章机构信息
          <el-tooltip class="item" effect="dark" placement="bottom-start">
            <div slot="content" class="w400">
              请仔细核对机构基本信息，如有信息错误或不全或无法搜索到机构，前往组织机构管理界面进行更新
            </div>
            <i class="el-icon-question f14 ml5" />
          </el-tooltip>
        </p>
        <el-row class="new-apply-wrapper">
          <el-col span={20}>
            <el-form-item class="text-right" label="机构信息" prop="areaOption">
              <el-cascader
                class={this.showAreaError ? 'is-error' : ''}
                ref="areaSelect"
                disabled={this.isBackApply}
                v-model={this.areaOption}
                placeholder="请先选择机构区域"
                options={this.options}
                onVisible-change={this.areaOptionBlur}
                show-all-levels={false}
                {...{
                  props: { props: this.cascaderProps },
                }}
              />
              {this.showAreaError && (
                <p class={styles.areaError}>请先选择机构区域</p>
              )}
            </el-form-item>
            <el-form-item prop="organizeName" label-width="0">
              <SelectTree
                ref="selectTree"
                class="query-select"
                loading={this.loadTree}
                parentId={this.area}
                value={this.sealData.organizeName}
                onInit={this.getAllTree}
                defaultExpended={this.defaultExpended}
                defaultProps={{ minSearchSize: 2 }}
                onHandleNodeClick={this.selectOrg}
                onInput={this.inputSelectTree}
                disabled={this.isBackApply}
                onError={this.selectTreeError}
              >
                <template slot="empty">
                  <SelectTreeEmpty />
                </template>
              </SelectTree>
            </el-form-item>
            {/* {this.isShowUpdateOrganization && <el-link type="primary" href="/home/organizationApply/organizationManagement">更新机构信息</el-link>} */}
          </el-col>
          {this.sealData.organizeUUID && (
            <div class="org">
              <div
                class={styles.orgInfo}
                style={{ marginTop: this.showAreaError ? '0' : '-10px' }}
              >
                <el-row>
                  <el-col
                    span={14}
                    class="over-hidden"
                    title={this.sealData.organizeName || ''}
                  >
                    机构名称：
                    {this.sealData.organizeName || (
                      <span class="red">信息缺失</span>
                    )}
                  </el-col>
                  <el-col span={10}>
                    机构类型：
                    {formatStatus(orgTypes, this.sealData.organizeType) || (
                      <span class="red">信息缺失</span>
                    )}
                  </el-col>
                  <el-col span={14}>
                    证照号码：
                    {this.sealData.organizeLicenseNumber || (
                      <span class="red">信息缺失</span>
                    )}
                  </el-col>
                  <el-col span={10}>
                    证照类型：
                    {formatStatus(
                      orgLicenseTypes,
                      this.sealData.organizeLicenseType
                    ) || <span class="red">信息缺失</span>}
                  </el-col>
                </el-row>
              </div>
              {(!this.sealData.organizeLicenseType ||
                !this.sealData.organizeLicenseNumber) && (
                <p class={styles.orgEdit}>
                  <el-button
                    onClick={() => {
                      this.wrongInfoDialogVisible = true
                    }}
                    type="text"
                  >
                    机构信息缺失或有误？去修改
                  </el-button>
                </p>
              )}
              {this.sealData.organizeName &&
                this.sealData.organizeType &&
                this.sealData.organizeLicenseType &&
                this.sealData.organizeLicenseNumber && (
                  <p class={styles.orgEdit}>
                    <el-button
                      onClick={() => {
                        this.wrongInfoDialogVisible = true
                      }}
                      type="text"
                    >
                      机构信息缺失或有误？去修改
                    </el-button>
                  </p>
                )}
            </div>
          )}
        </el-row>
        <p class={styles.panel}>
          <span class={styles.required}>*</span>申请印章信息
        </p>
        <el-row class="new-apply-wrapper top-position">
          <el-col span={24}>
            <el-form-item
              label="印章名称"
              prop="sealName"
              class={
                !!this.recommendName && 'is-error is-required is-no-asterisk'
              }
            >
              <el-input
                v-model={this.sealData.sealName}
                placeholder="印章名称只作为区别印章使用，与实际生成的印章名称无关，建议不超过50个字"
                onInput={this.sealNameChange}
                onBlur={this.sealNameBlur}
                autocomplete="off"
              />
              {!!this.recommendName && (
                <p class={styles.recommendName}>
                  <span class="red mr20">
                    印章名称已由{this.lastUser.agentName}
                    {(this.lastUser.agentName || '').indexOf('*') !== -1 && (
                      <el-button
                        type="text"
                        style="padding:0;min-width:60px;"
                        onClick={this.showRealName}
                      >
                        点击查看
                      </el-button>
                    )}
                    在{this.lastUser.sealNameUseTime}提交了
                    {formatStatus(useTypes, this.lastUser.sealUseType)}
                    印章申请，请勿重复申请。如有疑问请咨询：4000878198。
                  </span>
                  <br />
                  建议使用推荐名称：{this.recommendName}
                  <el-button type="text" onClick={this.useSealName}>
                    点击使用
                  </el-button>
                </p>
              )}
            </el-form-item>
          </el-col>
          <el-col span={24}>
            <el-form-item
              label="印章类别"
              class="person-seal-form-item"
              ref="sealType"
              prop="sealType"
            >
              <RadioGroup
                key="sealType"
                width={735}
                value={this.sealData.sealType}
                showIntro={
                  sealTypes.findIndex(
                    type => this.sealData.sealType === type.id
                  ) !== -1
                }
                {...{
                  on: {
                    'update:value': (val: any) => {
                      this.sealData.sealType = val
                    },
                  },
                }}
                radioRender={this.sealTypeRadioRender}
                data={sealTypes}
              />
            </el-form-item>
          </el-col>

          {this.isPersonSealApply && (
            <el-col span={24}>
              <el-form-item
                label="电子名章创建方式"
                prop="sealElectronicPicSubmitType"
                class="person-seal-form-item"
              >
                <RadioGroup
                  key="sealElectronicPicSubmitType"
                  width={560}
                  value={this.sealData.sealElectronicPicSubmitType}
                  showIntro={false}
                  disabled={false}
                  {...{
                    on: {
                      'update:value': (val: any) => {
                        this.sealData.sealElectronicPicSubmitType = val
                      },
                    },
                  }}
                  radioRender={this.personalSealRadioRender}
                  data={[
                    {
                      id: 1,
                      value: '手绘印章',
                      desc:
                        '面向无实体章的场景，需通过手机扫一扫绘制电子名章，无需手动加盖印模',
                      img: require('@/assets/seal/handwrite-black.png'),
                    },
                    {
                      id: 2,
                      value: '本地上传',
                      desc:
                        '面向有实体章的场景，需在下一步打印申请表后，手动加盖实体章印模',
                      img: require('@/assets/seal/upload.png'),
                    },
                  ]}
                />
              </el-form-item>
            </el-col>
          )}

          {this.isPersonHandWrite && (
            <el-col span={24}>
              {this.isPersonHandWrite && (
                <el-form-item
                  class="person-seal-form-item"
                  label="电子名章"
                  ref="personalHandWirteSeal"
                  prop="sealElectronicPicFileKey"
                >
                  {!this.handWriteSuccess ? (
                    <el-popover
                      popperClass={styles.drawSealPopper}
                      placement="right-start"
                      width="250"
                      trigger="hover"
                      content="通过手机扫一扫绘制电子名章，绘制完成的电子名章会自动保存"
                    >
                      <div
                        class={styles.drawSealBlock}
                        slot="reference"
                        onClick={this.handWrite}
                      >
                        {/* <i class="el-icon-edit" /> */}
                        <img
                          src={require('@/assets/seal/handwrite-blue.png')}
                          width="30px"
                          alt=""
                        />
                        <p>绘制电子名章</p>
                      </div>
                    </el-popover>
                  ) : (
                    <div class={styles.sealImageContainer}>
                      <el-image
                        ref="personalSeal"
                        src={this.handWriteSealUrl}
                        preview-src-list={[this.handWriteSealUrl]}
                      />
                      <div class={styles.sealMask}>
                        <i
                          class="el-icon-edit-outline"
                          onClick={this.handWrite}
                        />
                        <i class="el-icon-zoom-in" onClick={this.viewSeal} />
                      </div>
                    </div>
                  )}
                </el-form-item>
              )}
            </el-col>
          )}

          <el-col span={24}>
            <el-form-item
              label="用章方式"
              class="person-seal-form-item"
              ref="useType"
              prop="useType"
            >
              <RadioGroup
                key="useType"
                width={560}
                value={this.sealData.useType}
                showIntro={
                  useTypes.findIndex(
                    type => this.sealData.useType === type.id
                  ) !== -1
                }
                disabled={this.isBackApply}
                {...{
                  on: {
                    'update:value': (val: any) => {
                      this.sealData.useType = val
                    },
                  },
                }}
                radioRender={this.useTypeRadioRender}
                data={useTypes}
              />
            </el-form-item>
          </el-col>
          <el-col span={12} />
          {/* <el-col span={24}>
						<el-form-item label="电子印章服务费" class="line-height22">
							￥280/年
						</el-form-item>
					</el-col> */}
          <el-col span={24}>
            <el-form-item
              label="印章有效期 "
              style="width: 100%;"
              class="line-height22 "
            >
              <p class="color-bf f12">
                本系统制作的电子印章按年收费（¥280/年），有效期为1至5年。自印章制作完成后开始计算有效期，有效期满时需进入本系统申请延期后方可继续使用。
              </p>
              <el-radio-group
                v-model={this.sealData.sealUseTime}
                disabled={this.isBackApply}
              >
                {this.getSealUseTimeList().map((item: IStatus, i: number) => (
                  <el-radio disabled={this.isBackApply} label={item.id}>
                    {item.value}
                  </el-radio>
                ))}
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <p class={styles.panel}>
          <span class={styles.required}>*</span>上级审批机构
        </p>
        <el-row class="new-apply-wrapper">
          <el-col span={24}>
            <el-form-item
              label="上级审批机构"
              ref="auditOrg"
              prop="auditOrganizeUUID"
              class={styles.org}
            >
              {/* <el-input v-model={this.sealData.auditOrganizeName} autocomplete="off" /> */}
              <el-select
                v-model={this.sealData.auditOrganizeUUID}
                style={{ marginLeft: '0px' }}
                // filterable
                // remote
                placeholder="请选择上级审批机构"
                // remote-method={this.queryAuditOrg}
                onChange={this.selectAuditOrg}
                disabled={
                  !!this.sealData.sealType && this.sealData.sealType > 1
                }
                // loading="loading"
              >
                {this.auditOrgList &&
                  this.auditOrgList.map((org: any, i: number) => (
                    <el-option
                      label={org.organizeName}
                      value={org.organizeUUID}
                    />
                  ))}
              </el-select>
            </el-form-item>
          </el-col>
          {this.sealData.auditOrganizeUUID && (
            <div class="org">
              <div class={styles.orgInfo}>
                <el-row>
                  <el-col
                    span={24}
                    class="over-hidden"
                    title={this.sealData.auditOrganizeName || ''}
                  >
                    机构名称：
                    {this.sealData.auditOrganizeName || (
                      <span class="red">信息缺失</span>
                    )}
                  </el-col>
                  <el-col span={14}>
                    证照号码：
                    {this.sealData.auditOrganizeLicenseNumber || (
                      <span class="red">信息缺失</span>
                    )}
                  </el-col>
                  <el-col span={10}>
                    证照类型：
                    {formatStatus(
                      orgLicenseTypes,
                      this.sealData.auditOrganizeLicenseType
                    ) || <span class="red">信息缺失</span>}
                  </el-col>
                </el-row>
              </div>
            </div>
          )}
        </el-row>
      </div>
    )
  }

  // 是否个人电子名章申请
  get isPersonSealApply() {
    const personType = sealTypes.find(i => i.value === '电子名章')?.id

    return this.sealData && this.sealData.sealType === personType
  }

  get isPersonHandWrite() {
    return (
      this.isPersonSealApply && this.sealData.sealElectronicPicSubmitType === 1
    )
  }

  viewSeal() {
    this.handWritePreviewVisible = true
  }

  sealTypeRadioRender(item: any) {
    return (
      <div class={styles.sealTypeRadio}>
        <img
          src={require(`@/assets/seal/seal-${item.id}.png`)}
          style={{ width: 'auto', height: '64px' }}
        />
        <span>{item.value}</span>
      </div>
    )
  }

  useTypeRadioRender(item: any) {
    const option = useTypeOptions[item.id] || {}

    return (
      <div class={styles.useTypeRadio}>
        <div class={styles.imgBox}>
          <img
            src={option.img}
            style={{ width: option.imgWidth, height: option.imgHeight }}
          />
        </div>
        <div class={styles.textBox}>
          <h6>{item.value}</h6>
          <p>{option.subValue}</p>
        </div>
      </div>
    )
  }

  personalSealRadioRender(item: any) {
    return (
      <div class={[styles.useTypeRadio, styles.personSealRadio]}>
        <div class={styles.imgBox}>
          <img src={item.img} style={{ width: '26px', height: 'auto' }} />
        </div>
        <div class={styles.textBox}>
          <h6>{item.value}</h6>
          <p>{item.desc}</p>
        </div>
      </div>
    )
  }

  getSealUseTimeList(): IStatus[] {
    let ret = sealUseTimeList
    if (this.isBackApply) {
      ret = sealUseTimeList.filter((item: IStatus) => {
        return item.id === this.sealData.sealUseTime
      })
    }

    return ret.length ? ret : sealUseTimeList
  }

  handleRefreshQrCode() {
    this.handWrite()
  }

  async handWrite() {
    const res = await this.createElectronicSealTask({})
    this.qrInvalid = false
    setTimeout(() => {
      this.qrInvalid = true
      this.stop()
    }, 5 * 60 * 1000)
    const { taskId } = res.data
    const QRCode = require('qrcode')
    QRCode.toDataURL(
      `${window.location.origin}/hand-write?taskId=${taskId}`,
      {
        errorCorrectionLevel: 'H',
      },
      (err: any, url: string) => {
        this.qrCodeImg = url
      }
    )
    this.handWriteQrCodeVisible = true
    const requestFn = () => this.queryElectronicSealPic({ taskId })
    const judgeFn = (res: any) => {
      if (!!res.data.picUrl) {
        this.$message.success('电子名章绘制成功')
      }

      return !!res.data.picUrl
    }
    this.stop = pollRequest(requestFn, 3000, judgeFn, this.setHandWirteSeal)
  }

  setHandWirteSeal(res: any) {
    this.handWriteSealUrl = res.data.picUrl
    this.sealData.sealElectronicPicFileKey = res.data.fileKey
    this.handWriteQrCodeVisibleChange(false)
  }

  handWriteQrCodeVisibleChange(v: boolean) {
    this.handWriteQrCodeVisible = v
    if (!v) {
      this.stop()
    }
  }

  get newApplySecond() {
    // 新领申请第二步
    // class="new-apply-wrapper top-position"
    return (
      <div class={styles.printArea}>
        <h2>打印《电子印章申请表》</h2>

        {/* 预览图 */}
        <div ref="previewForm" class={styles.previewForm}>
          <figure onClick={this.togglePreviewLayer}>
            {this.isPersonHandWrite ? (
              <img src={require('@/assets/previewDemoForPerson.png')} />
            ) : (
              <img src={require('@/assets/previewDemo.png')} />
            )}
            <p>请稍候，图片处理中...</p>
          </figure>
          {this.isPersonHandWrite ? null : (
            <button class="reference-btn" onClick={this.showReference}>
              参考示例
            </button>
          )}
        </div>

        <div class={styles.printHelpInfo}>
          <h3>盖章说明</h3>
          <ul>
            <li>此申请表需加盖审批机构公章。</li>
            {this.isPersonHandWrite ? null : <li>请在表单内加盖印模。</li>}
            {this.isPersonHandWrite ? null : (
              <li>每张申请表只支持加盖一个印模，请确认加盖的印模清晰可辩。</li>
            )}
            <li>此印章申请表只受理机构保存。</li>
            <li>图片按照A4纸大小扫描，像素300dpi</li>
            {this.isPersonHandWrite ? null : (
              <li>
                组织机构的电子法定名称章需要上级主管部门审批，其他专用章（包括经济合同章、财务专用章登）在名称样式上应与单位正式章有所区别，操作流程如下：
              </li>
            )}
          </ul>
          {this.isPersonHandWrite ? null : (
            <img src={require('@/assets/applySealStep.png')} />
          )}
        </div>

        {/* 时时申请表单 */}
        {this.active === 1 && (
          <iframe
            ref="printHtml"
            src={this.printHtml}
            width="0"
            height="0"
            frameborder="0"
            onload={this.printLoaded}
          />
        )}
      </div>
    )
  }

  get newApplyThird() {
    // 新领申请第三步
    return (
      <div class={styles.uploadArea}>
        {this.isPersonHandWrite ? (
          <h2>上传《电子印章申请表》</h2>
        ) : (
          <h2>上传加盖印模后的《电子印章申请表》</h2>
        )}
        {/* <div class={styles.splice}>
					<el-button onClick={this.createApplyForm}>
						<img src={require("@/assets/create-form.png")} />
						生成印章申请表
					</el-button>
				</div> */}
        <div class={{ [styles.uploadContent]: true, 'new-apply': true }}>
          <Upload
            ref="upload"
            isPdf={this.isPdf}
            file={this.file}
            progress={this.fileProgress}
            progressType={'circle'}
            action={this.uploadUrl}
            success={this.uploadSuccess}
            error={this.uploadError}
            preview={this.preview}
            beforeUpload={this.beforeNewUpload}
          >
            <div
              class={{
                'personal-upload-help': this.isPersonHandWrite,
                'upload-help': true,
              }}
              slot="trigger"
              onClick={this.uploadConfirm}
            >
              <i class="el-icon-circle-plus" />
              <p>上传《电子印章申请表》</p>
            </div>
            <div
              class="upload-success"
              slot="success"
              onClick={this.stopUploaded}
            >
              <el-tooltip content="预览" placement="bottom" effect="light">
                <span
                  onClick={() => {
                    if (this.isPdf) {
                      // pdf预览
                      this.showPdfDialog(this.file.url)
                    } else {
                      this.previewSealImgs = [this.file.url]
                      this.togglePreviewLayer(undefined)
                    }
                  }}
                >
                  <img src={require('@/assets/viewIcon.png')} />
                </span>
              </el-tooltip>
              <el-tooltip content="重新上传" placement="bottom" effect="light">
                <span onClick={this.wakeUpload}>
                  <img src={require('@/assets/reUpload.png')} />
                </span>
              </el-tooltip>
            </div>
          </Upload>
          <div class={styles.tips}>
            <h3>上传须知</h3>
            <ul>
              <li>图片按照A4纸大小扫描，像素300dpi </li>
              <li>格式须为PNG/JPG/BMP/JPEG/GIF/PDF </li>
              <li>再次确认申请表中的印模、签字、盖章等重要信息清晰可辨</li>
              <li>申请表需要具有授权单位的盖章确认</li>
            </ul>
          </div>
        </div>

        {this.isPersonHandWrite ? null : (
          <button class="reference-btn" onClick={this.showReference}>
            参考示例
          </button>
        )}

        <p
          class={{
            [styles.validError]: true,
            [styles.error]: this.validImageError && !this.sealData.fileKey,
          }}
        >
          请上传印章申请表
        </p>
      </div>
    )
  }

  get payRender() {
    return (
      <div class={styles.orderWrapper}>
        <p class={styles.panel}>
          <span class={styles.required} />
          订单详情
        </p>
        <div class={styles.orderContent}>
          {this.orderInfo.payType === 1 && (
            <p class={styles.hint}>
              <img src={require('@/assets/scan.png')} />
              打开手机支付宝扫一扫，并输入指定金额付款
            </p>
          )}
          <div class={styles.payTypeSelect}>
            <el-row>
              <el-col span={12}>
                <el-form-item
                  label="付费方式"
                  label-width={this.formLabelWidth4}
                >
                  <el-radio-group
                    v-model={this.orderInfo.payType}
                    onChange={this.payTypeChange}
                  >
                    {payTypes &&
                      payTypes.map((item: IStatus, i: number) => {
                        if (this.orderPayTypes.includes(item.id)) {
                          return (
                            <el-radio label={item.id}>{item.value}</el-radio>
                          )
                        }

                        return ''
                      })}
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col span={12}>
                <el-form-item
                  label="使用年限"
                  label-width={this.formLabelWidth4}
                >
                  <span class="ml10">
                    {formatStatus(sealUseTimeList, this.sealData.sealUseTime)}
                  </span>
                </el-form-item>
              </el-col>
              <el-col span={15} class={styles.money}>
                {this.orderInfo.payType === 2 && (
                  <el-select
                    v-model={this.orderInfo.selectPayOrganize}
                    placeholder="请选择"
                    onChange={this.payTypeChange}
                  >
                    {this.orderInfo.payOrganizeInfos.map((item: any) => {
                      return (
                        <el-option
                          key={item.payerOrganizeUUID}
                          label={item.payerOrganizeName}
                          value={item.payerOrganizeUUID}
                        />
                      )
                    })}
                  </el-select>
                )}
                <h3>
                  应付金额 <span>总费用</span>
                </h3>
                <p>
                  ￥{this.orderInfo.payAmount}{' '}
                  <span>
                    (￥0硬件介质费+￥{this.orderInfo.payAmount}
                    电子印章服务费，含证书)
                  </span>
                </p>
              </el-col>
            </el-row>
            {this.orderInfo.payType === 1 && (
              <img
                class={styles.qrcode}
                src={require('@/assets/alipay-qrcode.png')}
              />
            )}
          </div>
        </div>
      </div>
    )
  }

  get finishRender() {
    // 新领申请第四步
    return (
      <div class={styles.successDiv}>
        <i class="el-icon-success" />
        <p class={styles.content}>
          {this.isBackApply ? '提交成功' : '创建成功'}
        </p>
        {this.type === 'newApply' ? (
          <el-button disabled={this.saveLoading} onClick={this.gotoDetail}>
            查看申请详情{this.second > 0 ? `（${this.second}秒）` : ''}
          </el-button>
        ) : (
          <el-button disabled={this.saveLoading} onClick={this.back}>
            返回列表{this.second > 0 ? `（${this.second}秒）` : ''}
          </el-button>
        )}
      </div>
    )
  }

  get revokeApplyFirst() {
    return (
      this.detailData &&
      this.detailData.map((item: any, index: number) => (
        <DetailItem
          class={{ [applyStyle.detailItem]: true, detailItem: true }}
          key={index}
          single={item.single}
          data={item.child}
          title={item.title}
        />
      ))
    )
  }

  get revokeApplySecond() {
    return (
      <div class={styles.sealForm}>
        {this.secondData &&
          this.secondData.map((item: any, index: number) => (
            <DetailItem
              class={{ [applyStyle.detailItem]: true, detailItem: true }}
              key={index}
              single={item.single}
              data={item.child}
              title={item.title}
            />
          ))}
        <p class={styles.panel}>
          <span class={styles.required}>*</span>吊销原因
        </p>
        <div>
          <el-radio-group v-model={this.sealData.reasonType} class="mt10">
            {/* <el-radio label={1}>Ukey签章</el-radio>
                    <el-radio label={2}>云签章</el-radio> */}
            {reasonList &&
              reasonList.map((item: IStatus, i: number) => (
                <el-radio key={`use${i}`} label={item.id}>
                  {item.value}
                </el-radio>
              ))}
          </el-radio-group>
          {this.sealData.reasonType === 4 && (
            <el-form-item prop="reason" class="mt10" label-width="0">
              <el-input
                type="textarea"
                rows={3}
                placeholder="请输入吊销原因"
                v-model={this.sealData.reason}
              />
            </el-form-item>
          )}
        </div>
        <p class={styles.panel}>吊销来源</p>
        <div class={styles.uploadContent}>
          <Upload
            file={this.file}
            progress={this.fileProgress}
            action={this.uploadUrl}
            success={this.uploadSuccess}
            error={this.uploadError}
            preview={this.preview}
            content="上传证明材料表"
            beforeUpload={this.beforeUpload}
          />
          <div class={styles.tips}>
            上传须知:
            <br /> 1、图片按照A4纸大小扫描，像素300dpi <br />
            2、格式须为PNG/JPG/BMP/JPEG/GIF
          </div>
        </div>
      </div>
    )
  }

  get lossApplySecond() {
    return (
      <div class={styles.sealForm}>
        {this.secondData &&
          this.secondData.map((item: any, index: number) => (
            <DetailItem
              class={{ [applyStyle.detailItem]: true, detailItem: true }}
              key={index}
              single={item.single}
              data={item.child}
              title={item.title}
            />
          ))}
        <p class={styles.panel}>
          {this.type === 'lossApply' ? (
            <span>
              <span class={styles.required}>*</span>挂失原因
            </span>
          ) : (
            '补发原因（选填）'
          )}
        </p>
        <div>
          <el-form-item prop="reason" class="mt10" label-width="0">
            <el-input
              type="textarea"
              rows={3}
              placeholder={
                this.type === 'lossApply' ? '请输入挂失原因' : '请输入补发原因'
              }
              v-model={this.sealData.reason}
            />
          </el-form-item>
        </div>
      </div>
    )
  }

  private get saveMethods() {
    // 提交审核的方法
    const methods: any = {
      revokeApply: this.saveAndSubmitRevoke,
      lossApply: this.lossSealApply,
      reissueApply: this.reissueApply,
    }

    return methods
  }

  private get stepList() {
    const newApply: any = [
      { id: 0, title: '填写' },
      { id: 1, title: '打印' },
      { id: 2, title: '上传' },
    ]
    if (!this.isBackApply) {
      newApply.push({ id: 3, title: '支付' })
    } else {
      newApply.push({ id: 3, title: '完成' })
    }
    const steps: any = {
      newApply: newApply,
      revokeApply: [
        { id: 0, title: '用户基本信息' },
        { id: 1, title: '吊销印章信息' },
        { id: 2, title: '完成' },
      ],
      lossApply: [
        { id: 0, title: '用户基本信息' },
        { id: 1, title: '挂失印章信息' },
        { id: 2, title: '完成' },
      ],
      reissueApply: [
        { id: 0, title: '用户基本信息' },
        { id: 1, title: '补发印章信息' },
        { id: 2, title: '完成' },
      ],
    }

    return steps
  }

  protected render() {
    return (
      <div
        class={{
          [styles.applyPage]: true,
          [styles.updatePage]: this.sealOption.length > 0,
        }}
        ref="applyPage"
      >
        <div
          class={{
            [styles.formDiv]: true,
            [applyStyle.sealDetail]: this.type !== 'newApply',
          }}
          style={{ width: this.sealOption.length > 0 ? '80%' : '100%' }}
        >
          {this.type !== 'newApply' ? (
            <el-steps active={this.active} align-center>
              {this.stepList[this.type] &&
                this.stepList[this.type].map((item: any) => (
                  <el-step key={item.id} title={item.title} />
                ))}
            </el-steps>
          ) : (
            <Steps
              style={{
                'border-bottom': '10px solid #f0f2f5',
                padding: '15px 0',
              }}
              index={this.active}
              stepData={this.stepList[this.type]}
            />
          )}
          <el-form
            hide-required-asterisk
            {...{ props: { model: this.sealData, rules: this.sealRules } }}
            class={{
              [styles.sealForm]: this.type === 'newApply',
              [applyStyle.sealForm]: this.type !== 'newApply',
              sealForm: true,
              [styles.sealFormWrapper]: true,
            }}
            label-width={this.type === 'newApply' ? '121px' : ''}
            label-position={this.updateFormLabelPosition()}
            ref="sealForm"
          >
            {this.active === 0 && this.firstContent}
            <div v-show={this.active === 1}>{this.secondContent}</div>
            <div v-show={this.active === 2}>{this.thirdContent}</div>
            {this.active === 3 ? this.paymentOrder() : ''}
            {/* {this.active === 2 && this.thirdContent} 使用这种方式会有问题，暂未定位到原因*/}
            {/* {this.active === 3 && this.payContent} */}
            {this.active === 4 && this.finishContent}
            {/* {this.showTimeline && (
              <OptionLine sealOption={this.sealOption} />
            )} */}
          </el-form>
          {this.operations}
        </div>
        {this.sealOption.length > 0 && (
          <OptionLine
            theme={2}
            sealOption={this.sealOption}
            class={styles.optionLine}
          />
        )}

        <PrintDialog
          onVisibleChange={(val: boolean) => {
            this.setStateData({ printVisible: val })
          }}
          visible={this.printVisible}
          printHtml={this.printHtml}
        />
        <ImagePreview
          visible={this.imgVisible}
          title={this.type === 'newApply' ? '申请表预览' : '证明材料'}
          url={this.file.url}
          onVisibleChange={(val: boolean) => {
            this.imgVisible = val
          }}
        />
        <ApplyLicenseNumber
          visible={this.visible}
          defaultData={this.sealData}
          onVisibleChange={(val: boolean) => {
            this.setStateData({ visible: val })
          }}
          currentOrganizeUUID={this.currentOrganizeUUID}
          onSubmit={this.applyLicenseNumberSubmit}
        />

        <PreviewImages
          show={this.previewImageShow}
          list={this.previewSealImgs}
          {...{
            on: {
              'update:show': (val: boolean) => {
                this.previewImageShow = val
              },
            },
          }}
          close-with-backdrop
        >
          {this.showPrintBtn && (
            <span onClick={this.print}>
              <i class="el-icon-printer" />
            </span>
          )}
        </PreviewImages>
        <SelectDialog
          dialogVisible={this.wrongInfoDialogVisible}
          {...{
            on: {
              'update:dialogVisible': this.setDialogVisible,
            },
          }}
          options={wrongInfoOptions}
          onselected={this.handleDialogSelected}
          title="请选择错误类型"
        />
        <PdfViewDialog
          dialogVisible={this.pdfDialogVisible}
          url={this.pdfUrl}
          {...{
            on: {
              'update:dialogVisible': (val: boolean) => {
                this.pdfDialogVisible = val
              },
            },
          }}
        />
        <el-dialog
          title={this.isUploadExample ? '上传《电子印章申请表》' : '参考示例'}
          custom-class="preview-dialog"
          visible={this.exampleVisible}
          close-on-click-modal={false}
          close-on-press-escape={false}
          width="1000px"
          {...{
            on: {
              'update:visible': (val: boolean) => {
                this.exampleVisible = val
              },
              closed: () => {
                this.stopShowingExample = false
              },
            },
          }}
        >
          <div class={styles.exampleContent}>
            <p class={styles.tips}>
              <i class="el-icon-info" />
              请上传加盖印模后的《电子印章申请表》，未加盖印模申请表将无法通过系统审核
            </p>
            {this.showIndex !== 1 && (
              <span
                class={styles.circleLeft}
                onClick={() => {
                  this.showIndex -= 1
                }}
              >
                <i class="el-icon-arrow-left" />
              </span>
            )}
            {this.showIndex !== this.exampleUrl.length && (
              <span
                class={styles.circleRight}
                onClick={() => {
                  this.showIndex += 1
                }}
              >
                <i class="el-icon-arrow-right" />
              </span>
            )}
            {this.exampleUrl.map((example: any, index: number) => (
              <div v-show={this.showIndex === index + 1}>
                <h4>{example.title}</h4>
                <img src={example.url} />
              </div>
            ))}
          </div>
          <span slot="footer">
            {this.showIndex === this.exampleUrl.length && this.isUploadExample && (
              <el-checkbox class="pr20" v-model={this.stopShowingExample}>
                今日不再显示
              </el-checkbox>
            )}
            {(!this.isUploadExample ||
              (this.isUploadExample &&
                this.showIndex === this.exampleUrl.length)) && (
              <el-button onClick={this.closeExample}>
                {this.isUploadExample ? `取消` : `关闭`}
              </el-button>
            )}
            {this.showIndex !== this.exampleUrl.length && (
              <el-button type="primary" onClick={this.nextPage}>
                下一页
              </el-button>
            )}
            {this.showIndex === this.exampleUrl.length && this.isUploadExample && (
              <el-button type="primary" onClick={this.confirmExample}>
                上传
              </el-button>
            )}
          </span>
        </el-dialog>
        <HandWriteQrCode
          visible={this.handWriteQrCodeVisible}
          imgUrl={this.qrCodeImg}
          qrInvalid={this.qrInvalid}
          onRefreshQrCode={this.handleRefreshQrCode}
          {...{
            on: {
              'update:visible': this.handWriteQrCodeVisibleChange,
            },
          }}
        />
        <ImagePreview
          title="签名预览"
          url={this.handWriteSealUrl}
          visible={this.handWritePreviewVisible}
          onVisibleChange={(val: boolean) => {
            this.handWritePreviewVisible = val
          }}
        />
      </div>
    )
  }

  get printHtml() {
    return `/applyForm?t=${Date.now()}&isPersonSealApply=${
      this.isPersonHandWrite
    }`
  }

  @Watch('active')
  private activeChange(val: number) {
    this.$nextTick(() => {
      ;(this.$refs.sealForm as ElForm).clearValidate()
      ;(this.$refs.applyPage as Element).scrollIntoView() // 置顶

      // 打印时，更新表单数据，生成新图片
      if (val === 1 && this.type === 'newApply') {
        this.previewSealImgs = []
        const ifremaEl: any = this.$refs.printHtml
        ifremaEl.src = this.printHtml

        this.updatePreviewMsg('请稍候，图片处理中...')
      }
    })
    if (
      this.isBackApply &&
      val === this.stepList[this.type || 'newApply'].length - 1
    ) {
      this.$router.replace({
        name: 'applyPage',
        params: { type: this.type },
      })
      clearInterval(this.successInterval)
      this.second = 5
      this.successInterval = setInterval(() => {
        if (this.second === 0) {
          clearInterval(this.successInterval)
          // this.second = 3
          this.gotoDetail()
        } else {
          this.second--
        }
      }, 1000)
    }
    this.validImageError = false
  }

  setDialogVisible(v: boolean) {
    this.wrongInfoDialogVisible = v
  }

  private gotoDetail() {
    this.$router.push({
      name: 'applyFlow',
      params: { type: 'newApply' },
      query: { id: this.applyId, payType: this.orderInfo.payType },
    })
  }

  @Watch('user.accountUUID')
  private userChange(val: string) {
    if (!this.applyId) {
      if (this.sealSn) {
        this.setSealData(this.data || {})
      } else {
        this.resetSealData()
      }
    }
  }

  @Watch('sealData.sealElectronicPicFileKey')
  private sealElectronicPicFileKeyChange() {
    const sealForm = this.$refs.sealForm as ElForm
    sealForm.validateField('sealElectronicPicFileKey')
  }

  @Watch('sealData.useType')
  private useTypeChange() {
    const sealForm = this.$refs.sealForm as ElForm
    sealForm.validateField('useType')
  }

  @Watch('sealData.sealElectronicPicSubmitType')
  private sealElectronicPicSubmitTypeChange() {
    const sealForm = this.$refs.sealForm as ElForm
    sealForm.validateField('sealElectronicPicSubmitType')
    const personalHandWirteSeal = this.$refs.personalHandWirteSeal as ElFormItem
    personalHandWirteSeal && personalHandWirteSeal.clearValidate()
  }

  @Watch('areaOption')
  private areaOptionChange(val: any) {
    this.area = typeof val === 'object' ? val[val.length - 1] : val
    this.areaOptionBlur(false)
  }

  @Watch('area')
  private areaChange(val: any, old: any) {
    // debugger
    this.selectOrg({})
  }

  private async mounted() {
    this.setStateData({ type: this.$route.params.type })
    // this.user.organizeUUID && this.queryAuditOrg(this.user.organizeUUID)
    this.applyId = this.$route.query.id || ''
    this.sealSn = this.$route.query.sealSn || ''
    this.detailData = []
    if (this.type === 'newApply') {
      // 特殊处理，跳转到订单确认
      this.active = this.$route.query.ic === 'true' ? 3 : 0
      this.getAreaList()
      if (!!this.applyId) {
        // 编辑
        this.sealData.sealApplyId = parseInt(this.applyId, 10)
        this.getDetail()
      } else {
        // 新增
        this.sealData.sealApplyId = 0
        this.resetSealData()
      }
    } else {
      if (this.applyId) {
        this.setApplyDetail(this.applyId)
      } else if (this.sealSn) {
        this.data = await this.sealDetail(this.sealSn)
        this.setSealData(this.data)
      } else {
        // 异常状态
        this.$router.back()
      }
    }
    this.init()
  }

  private init() {
    this.sealRules['reason'][0].required = `${this.type}` !== 'reissueApply'
    this.sealRules['reason'][0].message =
      `${this.type}` === 'reissueApply'
        ? '补发原因不能为空'
        : `${this.type}` === 'lossApply'
        ? '挂失原因不能为空'
        : '吊销原因不能为空'
  }

  private setApplyDetail(sealApplyId: number) {
    this.applyDetail(sealApplyId).then((data: any) => {
      this.sealApplyStatus = data.sealApplyStatus
      if (
        data.sealApplyStatus === 1 ||
        data.sealApplyStatus === 90 ||
        data.sealApplyStatus === 91 ||
        data.sealApplyStatus === 92
      ) {
        this.update(data)
      } else {
        this.active = 2
      }
    })
  }

  private update(data: any) {
    const itemData = detailData2.concat(lastDetail)
    const secondData = sealDetail
    const datas = Object.assign({}, data, {
      agentName: data.agentName,
      agentLicenseType: data.agentLicenseType,
      agentLicenseTypeName: formatStatus(
        userLicenseTypes,
        data.agentLicenseType
      ),
      agentMobile: data.agentMobile,
      agentLicenseNumber: data.agentLicenseNumber,
      agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
      agentMobileDes: desensitization(data.agentMobile || ''),
      reasonContent: data.applyReason,
      fileKey: data.sealApplyFileKey,
      url: data.sealApplyFileUrl,
      sealSn: data.sealSn,
      sealApplyId: data.sealApplyId,
      sealName: data.sealName,
      startTime: data.sealStartTime,
      endTime: data.sealEndTime,
      organizeName: data.applyOrganizeName,
      organizeCardType: formatStatus(
        orgLicenseTypes,
        data.applyOrganizeLicenseType
      ),
      organizeType: formatStatus(orgTypes, data.applyOrganizeType),
      organizeCardId: data.applyOrganizeLicenseNumber,
      organizeLevel: formatStatus(adminTypes, data.applyOrganizeLevel),
      sealType: formatStatus(sealTypes, data.sealType),
      sealUseType: formatStatus(useTypes, data.sealUseType),
    })
    itemData.forEach((detail: any) => {
      detail.child.forEach((item: any) => {
        item.content = datas[item.key]
      })
    })
    secondData.forEach((detail: any) => {
      detail.child.forEach((item: any) => {
        item.content = datas[item.key]
      })
    })
    this.sealData = Object.assign({}, sealData, datas)
    this.isPdf = data.sealApplyFileKeyType === 'pdf'
    this.sealData.reasonType = filterReasonId(this.sealData.reasonContent || '')
    if (this.sealData.reasonType === 4) {
      this.sealData.reason = this.sealData.reasonContent
    }
    this.detailData = itemData
    this.secondData = secondData
    if (!!this.sealData.fileKey) {
      this.file = Object.assign(
        {},
        { name: '证明材料表', status: 'done', size: 0, url: this.sealData.url }
      )
    } else {
      this.file = {}
    }
    this.sealOption = getTimeline(data.sealApplyStatus, this.sealData)
    this.$nextTick(() => {
      this.$refs.sealForm && (this.$refs.sealForm as ElForm).clearValidate()
    })
  }

  private setSealData(data: any) {
    // 通过印章详情设置申请信息
    const itemData = detailData2.concat(lastDetail)
    // this.type === "revokeApply" ? detailData.concat(detailData2).concat(lastDetail) :
    const secondData = sealDetail
    const datas = Object.assign(
      {},
      data,
      {
        organizeType: formatStatus(orgTypes, data.organizeType),
        organizeCardType: formatStatus(orgLicenseTypes, data.organizeCardType),
        organizeLevel: formatStatus(adminTypes, data.organizeLevel),
        inspectCardType: formatStatus(userLicenseTypes, data.inspectCardType),
        sealType: formatStatus(sealTypes, data.sealType),
        sealUseType: formatStatus(useTypes, data.sealUseType),
        inspectMobileDes: desensitization(data.inspectMobile),
        inspectCardIdDes: desensitization(data.inspectCardId),
        agentLicenseTypeName: formatStatus(
          userLicenseTypes,
          this.user.accountLicenseType
        ),
      },
      {
        agentName: this.user.accountName,
        agentId: this.user.accountUUID,
        agentMobile: this.user.accountMobile,
        agentLicenseType: this.user.accountLicenseType,
        agentLicenseNumber: this.user.accountLicenseNumber,
        agentMobileDes: desensitization(this.user.accountMobile),
        agentLicenseNumberDes: desensitization(this.user.accountLicenseNumber),
        agentLicenseTypeName: formatStatus(
          userLicenseTypes,
          this.user.accountLicenseType
        ),
      }
    )
    itemData.forEach((detail: any) => {
      detail.child.forEach((item: any) => {
        item.content = datas[item.key]
      })
    })
    secondData.forEach((detail: any) => {
      detail.child.forEach((item: any) => {
        item.content = datas[item.key]
      })
    })
    this.sealData = Object.assign({}, sealData, datas)
    this.sealData.reasonType = filterReasonId(this.sealData.reasonContent || '')
    if (this.sealData.reasonType === 4) {
      this.sealData.reason = this.sealData.reasonContent
    }
    this.detailData = itemData
    this.secondData = secondData
    if (!!this.sealData.fileKey) {
      this.file = Object.assign(
        {},
        { name: '证明材料表', status: 'done', size: 0, url: this.sealData.url }
      )
    } else {
      this.file = {}
    }
    this.$nextTick(() => {
      this.$refs.sealForm && (this.$refs.sealForm as ElForm).clearValidate()
    })
  }

  private beforeDestroy() {
    this.successInterval && clearInterval(this.successInterval)
  }

  private getAreaList() {
    this.getAreas().then((data: any) => {
      this.areas = data
      // this.area = (this.areas[0] || { uuid: "" }).uuid;
      this.options = data
    })
  }

  private showRealName() {
    if (!!this.lastUser.agentUuid) {
      this.accountDataMasking({ accountUUID: this.lastUser.agentUuid }).then(
        (res: any) => {
          if (!!this.lastUser.agentName) {
            this.lastUser.agentName = res.data.name
          }
        }
      )
    }
  }

  private getDetail() {
    this.applyDetail(this.sealData.sealApplyId).then((data: any) => {
      this.handWriteSealUrl = data.electronicSealPicUrl
      this.sealApplyStatus = data.sealApplyStatus
      if (
        data.sealApplyStatus !== 1 &&
        data.sealApplyStatus !== 90 &&
        data.sealApplyStatus !== 91 &&
        data.sealApplyStatus !== 92 &&
        data.sealApplyStatus !== 93
      ) {
        this.$message.error('当前状态下印章无法编辑')
        this.errorPage = true
      }
      this.setStateData({
        orgList: [
          {
            organizeName: data.applyOrganizeName,
            organizeUUID: data.applyOrganizeUuid,
            organizeAdministrationLevel: data.applyOrganizeLevel,
            organizeLicenseNumber: data.applyOrganizeLicenseNumber,
            organizeLicenseType: data.applyOrganizeLicenseType,
            organizeType: data.applyOrganizeType,
          },
        ],
        auditOrgList: [
          {
            organizeName: data.confirmOrganizeName,
            organizeUUID: data.confirmOrganizeUuid,
            organizeLicenseNumber: data.confirmOrganizeLicenseNumber,
            organizeLicenseType: data.confirmOrganizeLicenseType,
          },
        ],
      })

      this.queryAuditOrg(this.user.organizeUUID)
      this.$nextTick(() => {
        this.sealData = Object.assign({}, data, {
          agentLicenseNumber: data.agentLicenseNumber,
          agentLicenseType: data.agentLicenseType,
          agentName: data.agentName,
          agentMobile: data.agentMobile,
          organizeAdministrationLevel: data.applyOrganizeLevel,
          organizeLicenseNumber: data.applyOrganizeLicenseNumber,
          organizeLicenseType: data.applyOrganizeLicenseType,
          organizeName: data.applyOrganizeName,
          organizeType: data.applyOrganizeType,
          organizeUUID: data.applyOrganizeUuid,
          useType: data.sealUseType,
          sealType: data.sealType,
          sealName: data.sealName,
          auditOrganizeName: data.confirmOrganizeName,
          auditOrganizeLicenseType: data.confirmOrganizeLicenseType,
          auditOrganizeLicenseNumber: data.confirmOrganizeLicenseNumber,
          auditOrganizeUUID: data.confirmOrganizeUuid,
          fileKey: data.sealApplyFileKey,
          url: data.sealApplyFileUrl,
          agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
          agentMobileDes: desensitization(data.agentMobile || ''),
          sealApplyId: data.sealApplyId,
          orderNo: data.partnerOrderNo,
          sealElectronicPicFileKey: data.electronicSealPic,
          sealElectronicPicSubmitType: data.electronicSealPicSubmitType,
        })
        this.isPdf = data.sealApplyFileKeyType === 'pdf'
        ;(this.$refs['selectTree'] as any) &&
          (this.$refs['selectTree'] as any).setValue(
            data.applyOrganizeName || ''
          )
        this.sealOption = getTimeline(data.sealApplyStatus, this.sealData)
        this.sealApplyStatus = data.sealApplyStatus
        if (!!this.sealData.fileKey) {
          this.file = Object.assign(
            {},
            {
              name: '印章申请表',
              status: 'done',
              size: 0,
              url: this.sealData.url,
            }
          )
        } else {
          this.file = {}
        }
      })
    })
  }

  private selectArea() {
    ;(this.$refs['selectTree'] as any) &&
      (this.$refs['selectTree'] as any).setVisible(false)
    ;(this.$refs['selectTree'] as any) &&
      (this.$refs['selectTree'] as any).setValue('')
    this.selectOrg({})
    // this.
  }

  private async resetSealData() {
    this.setStateData({
      orgList: [
        {
          organizeName: !this.user.organizeName ? '' : this.user.organizeName,
          organizeUUID: this.user.organizeUUID,
          organizeAdministrationLevel: this.user.organizeAdministrationLevel,
          organizeLicenseNumber: this.user.organizeLicenseNumber,
          organizeLicenseType: this.user.organizeLicenseType,
          organizeType: this.user.organizeType,
        },
      ],
      auditOrgList: [],
    })
    this.file = {}
    await this.queryAuditOrg(this.user.organizeUUID)
    this.$nextTick(() => {
      this.sealData = Object.assign({}, sealData, {
        agentName: this.user.accountName,
        agentId: this.user.accountUUID,
        agentMobile: this.user.accountMobile,
        agentLicenseType: this.user.accountLicenseType,
        agentLicenseNumber: this.user.accountLicenseNumber,
        organizeName: !this.user.organizeName ? '' : this.user.organizeName,
        organizeUUID: this.user.organizeUUID,
        organizeType: this.user.organizeType,
        organizeAdministrationLevel: this.user.organizeAdministrationLevel,
        organizeLicenseType: this.user.organizeLicenseType,
        organizeLicenseNumber: this.user.organizeLicenseNumber,
        agentLicenseNumberDes: desensitization(
          this.user.accountLicenseNumber || ''
        ),
        agentMobileDes: desensitization(this.user.accountMobile || ''),
        sealName: '',
      })

      this.sealData = Object.assign(this.sealData, {
        auditOrganizeUUID: this.sealData.organizeUUID,
        auditOrganizeLicenseNumber: this.sealData.organizeLicenseNumber,
        auditOrganizeLicenseType: this.sealData.organizeLicenseType,
        auditOrganizeName: this.sealData.organizeName,
      })
      this.$nextTick(() => {
        ;(this.$refs.sealForm as ElForm) &&
          (this.$refs.sealForm as ElForm).clearValidate()
        ;(this.$refs['selectTree'] as any) &&
          (this.$refs['selectTree'] as any).setValue &&
          (this.$refs['selectTree'] as any).setValue(
            this.user.organizeName || ''
          )
      })
    })
    // this.orgList = []
  }

  private inputSelectTree(val: string) {
    this.$nextTick(() => {
      ;(this.$refs.sealForm as ElForm) &&
        (this.$refs.sealForm as ElForm).clearValidate()
    })
  }

  @Watch('sealData.sealType')
  private sealTypeChange(val: number) {
    const sealForm = this.$refs.sealForm as ElForm
    sealForm.validateField('sealType')
    if (val !== 1) {
      // this.auditOrgs = Object.assign([], this.orgList);
      // this.sealData.auditOrganizeUUID = this.sealData.organizeUUID;
      this.sealData = Object.assign(this.sealData, {
        auditOrganizeUUID: this.sealData.organizeUUID,
        auditOrganizeLicenseNumber: this.sealData.organizeLicenseNumber,
        auditOrganizeLicenseType: this.sealData.organizeLicenseType,
        auditOrganizeName: this.sealData.organizeName,
      })
    }
    // this.auditOrgs = [];
    this.$nextTick(() => {
      this.$refs.auditOrg && (this.$refs.auditOrg as ElFormItem).clearValidate()
      this.$refs.auditOrganizeLicenseNumber &&
        (this.$refs.auditOrganizeLicenseNumber as ElFormItem).clearValidate()
      this.$refs.auditOrganizeLicenseType &&
        (this.$refs.auditOrganizeLicenseType as ElFormItem).clearValidate()
    })
  }

  private payTypeChange(v: any) {
    this.querySealApplyPayPreOrderInfo.forEach((e: any) => {
      if (e.payType === v) {
        this.orderInfo = {
          ...e,
          selectPayOrganize: e.payOrganizeInfos[0].payerOrganizeUUID,
        }
      }
    })
  }

  private areaOptionBlur(val: boolean) {
    if (!val) {
      this.showAreaError = !this.areaOption || this.areaOption.length === 0
    }
  }

  private sealNameChange(val: string) {
    this.sealData.sealName = (val || '').trim()
    this.editedSealName = true
    this.recommendName = ''
    this.lastUser = {}
  }

  private useSealName() {
    this.sealData.sealName = this.recommendName
    this.recommendName = ''
    this.lastUser = {}
  }

  private sealNameBlur(e: any) {
    return new Promise((resolve, reject) => {
      ;(this.$refs.sealForm as ElForm) &&
        (this.$refs.sealForm as ElForm).validateField(
          'sealName',
          (val: string) => {
            if (!val) {
              // 校验通过判断印章重复
              if (!!this.recommendName) {
                resolve(false)

                return
              }
              this.checkSealNameRepeat({ sealName: this.sealData.sealName })
                .then((res: any) => {
                  if (res.data.checkStatus) {
                    resolve(true)
                  } else {
                    this.recommendName = res.data.name
                    this.lastUser = res.data
                    resolve(false)
                  }
                })
                .catch((e: any) => {
                  reject()
                })
            }
          }
        )
    })
  }

  private async notSubmit() {
    this.validImageError = false
    this.saveLoading = true
    this.onlySave()
      .then((res: any) => {
        this.saveLoading = false
        this.back()
      })
      .catch((e: any) => {
        this.saveLoading = false
      })
  }

  private async onlySave() {
    return await this.saveSeal(this.sealData)
  }

  private async saveAndSubmitOrder() {
    this.$refs['orderForm'] &&
      (this.$refs['orderForm'] as ElForm).validate((val: boolean) => {
        if (val) {
          this.finishQRCodePayOrder({
            sealApplyId: this.sealData.sealApplyId,
            orderNumber: this.sealData.orderNo,
          })
            .then((res: any) => {
              this.saveLoading = false
              this.showOrderDialog = false
              this.active++
            })
            .catch((e: any) => {
              this.saveLoading = false
            })
        }
      })
  }

  private getOrderInfo() {
    this.querySealApplyPayOrderInfo(this.sealData.sealApplyId).then(
      (res: any) => {
        this.orderInfo = res
      }
    )
  }

  toastFormError(invalidFields: any = {}) {
    const keys: string[] = Object.keys(invalidFields)
    if (keys && keys.length) {
      const key = keys[0]
      this.$message.error(invalidFields[key][0].message)
    }
  }

  private invalidForm() {
    if (!this.sealData.organizeLicenseNumber) {
      this.applyLicenseNumberHandler(true)

      return true
    } else if (!this.sealData.auditOrganizeLicenseNumber) {
      this.$message.error('您所选的上级审批机构证照信息为空，请重新选择')

      return true
    }

    return false
  }

  private next() {
    // 让印章名称为空，不设置默认值
    // 1.非编辑状态
    // 2.在第一步跳转第二步时
    // 3.印章名称没有编辑过
    // 在上面3个条件同时达到时，清空印章的名称
    if (!this.$route.query.id && !this.active && !this.editedSealName) {
      if (this.sealData.sealName) {
        this.sealData.sealName = ''
      }
    }

    // 添加对金额的验证，以防止用户在上传时，多多点操作直接完成支付
    // 同时也控制金额为0时无法完成支持
    const payComponent: any = this.$refs.orderSubmitRef

    if (payComponent && payComponent.getAllAmount() <= 0) return
    ;(this.$refs['selectTree'] as any) &&
      (this.$refs['selectTree'] as any).setValue(
        this.sealData.organizeName || ''
      )
    ;(this.$refs.sealForm as ElForm).validate(
      async (valid: boolean, invalidFields: object) => {
        if (invalidFields) {
          this.toastFormError(invalidFields)
        }
        if (valid) {
          if (this.invalidForm()) return
          this.showAreaError = false
          if (this.active === 0) {
            // 仅保存
            this.saveLoading = true
            this.sealNameBlur({})
              .then(async (res: any) => {
                if (!res) {
                  this.saveLoading = false
                  this.$message.error('印章名称已被使用')

                  return
                }
                await this.onlySave()
                  .then((res: any) => {
                    this.saveLoading = false
                    this.$router.replace({
                      name: 'applyPage',
                      params: { type: this.type },
                      query: { id: res.data.sealApplyId },
                    })
                    this.sealData.sealApplyId = res.data.sealApplyId
                    this.active++
                    sessionStorage.setItem(
                      'sealInfo',
                      JSON.stringify({
                        organize: this.sealData.organizeName,
                        orgType: formatStatus(
                          orgTypes,
                          this.sealData.organizeType
                        ),
                        licenseType: formatStatus(
                          orgLicenseTypes,
                          this.sealData.organizeLicenseType
                        ),
                        licenseNumber: this.sealData.organizeLicenseNumber,
                        agentName: this.sealData.agentName,
                        agentLicenseType: formatStatus(
                          userLicenseTypes,
                          this.sealData.agentLicenseType
                        ),
                        agentLicenseNumber: this.sealData.agentLicenseNumber,
                        agentMobile: this.sealData.agentMobile,
                        sealName: this.sealData.sealName,
                        useType: formatStatus(useTypes, this.sealData.useType),
                        auditOrg: this.sealData.auditOrganizeName,
                        isUpdate: this.sealData.licenseNumberSource === 2,
                        handWriteSealUrl: this.handWriteSealUrl,
                      })
                    )
                  })
                  .catch((e: any) => {
                    this.saveLoading = false
                  })
              })
              .catch((e: any) => {
                this.saveLoading = false
              })
          } else if (this.active === 2) {
            if (!this.sealData.fileKey) {
              // 提交并
              this.validImageError = true
            } else {
              this.validImageError = false
              this.saveLoading = true
              await this.sealApplyPicSubmit({
                fileKey: this.sealData.fileKey,
                sealApplyId: this.sealData.sealApplyId,
              })
                .then((res: any) => {
                  this.saveLoading = false
                  this.active = this.isBackApply
                    ? this.active + 2
                    : this.active + 1
                })
                .catch((e: any) => {
                  this.saveLoading = false
                })
            }
          } else if (this.active === 3) {
            if (this.saveLoading) return
            this.saveLoading = true
            this.orderSubmitRef &&
              this.orderSubmitRef
                .toPay()
                .then(() => {
                  // this.saveLoading = true
                })
                .catch((e: any) => {
                  this.saveLoading = false
                })
          }
          // else if (this.active === 3) {
          // 	this.createOrder({
          // 		sealApplyId: this.sealData.sealApplyId,
          // 		payerOrganizeUUID: this.orderInfo.selectPayOrganize,
          // 		payType: this.orderInfo.payType
          // 	}).then((res: any) => {

          // 		if (this.orderInfo.payType === 1) {
          // 			this.showOrderDialog = true;
          // 		}
          // 	}).catch((e: any) => {
          // 		this.saveLoading = false;
          // 	})
          // }
          else if (this.active === 1) {
            this.active++
          }
        }
      }
    )
  }
  // 修改表单对齐方式
  private updateFormLabelPosition(): string {
    if ((this.active === 1 || this.active === 2) && this.type === 'newApply') {
      return 'top'
    }

    return 'right'
  }

  private showPdfDialog(url: string) {
    this.pdfDialogVisible = true
    this.pdfUrl = url
  }

  private submitToAudit() {
    this.createOrder({
      sealApplyId: this.sealData.sealApplyId,
      payerOrganizeUUID: this.orderInfo.selectPayOrganize,
      payType: this.orderInfo.payType,
    })
      .then((res: any) => {
        this.sealApplyUnifiedSubmit(this.sealData.sealApplyId).then(
          (res: any) => {
            this.saveLoading = false
            this.active++
          }
        )
      })
      .catch((e: any) => {
        this.saveLoading = false
      })
  }

  private notSubmitRevoke(data: any) {
    this.saveRevokeSeal(data)
      .then((res: any) => {
        this.saveLoading = false
        this.back()
      })
      .catch((e: any) => {
        this.saveLoading = false
      })
  }

  private nextRevoke(flag: boolean = false) {
    if (flag) {
      this.back()

      // 仅保存
      // this.notSubmitRevoke(data);
      return
    }
    if (this.active === 1) {
      ;(this.$refs.sealForm as ElForm).validate(async (valid: boolean) => {
        if (valid) {
          const data: any = Object.assign({}, this.sealData, {
            reason:
              this.sealData.reasonType === 4
                ? this.sealData.reason
                : filterReasonValue(this.sealData.reasonType),
          })
          const postData =
            this.type === 'revokeApply'
              ? data
              : {
                  sealApplyId: this.applyId,
                  sealSn: data.sealSn,
                  applyReason: data.reason,
                }
          this.saveLoading = true

          this.saveMethods[this.type](postData)
            .then((res: any) => {
              this.saveLoading = false
              this.active++
            })
            .catch((e: any) => {
              this.saveLoading = false
            })
        }
      })
    } else if (this.active === 0) {
      this.active++
    }
  }

  private preview() {
    this.imgVisible = true
  }

  private validField() {
    return (
      !!this.sealData.sealName &&
      !!this.sealData.organizeName &&
      !!this.sealData.organizeLicenseType &&
      !!this.sealData.organizeLicenseNumber &&
      !!this.sealData.organizeType &&
      !!this.sealData.agentName &&
      !!this.sealData.agentMobile &&
      !!this.sealData.agentLicenseType &&
      !!this.sealData.agentLicenseNumber &&
      !!this.sealData.sealType &&
      !!this.sealData.useType &&
      !!this.sealData.auditOrganizeName &&
      !!this.sealData.auditOrganizeLicenseType &&
      !!this.sealData.auditOrganizeLicenseNumber &&
      !!this.sealData.fileKey
    )
  }
  private inputChange(val: any) {
    return this.sealData
  }

  private back() {
    // if(this.type === 'newApply' || )
    this.$router.back()
  }

  private fileProgress(event: any, file: any, fileList: any[]) {
    this.file = Object.assign(
      {},
      {
        name: file.name,
        status: 'upload',
        size: file.size,
        precent: parseInt(file.percentage),
      }
    )
  }

  private uploadSuccess(response: any, file: any, fileList: any[]) {
    if (response.errCode === 0) {
      this.file = Object.assign(
        {},
        {
          name: file.name,
          status: 'done',
          size: file.size,
          url: response.data.fileUrl,
        }
      )
      this.isPdf = response.data.fileType === 'pdf'
      this.sealData.fileKey = response.data.fileKey
    } else {
      this.file = {}
      this.sealData.fileKey = ''
      this.sealData.url = ''
      this.$message.error(response.msg)
    }
  }

  private uploadError(err: any, file: any, fileList: any[]) {
    this.file = {}
    this.sealData.fileKey = ''
    this.sealData.url = ''
    this.$message.error('文件上传失败')
  }

  private beforeNewUpload(file: any) {
    const isJPG =
      fileTypes.filter(
        (item: string) => item === (file.type || '').toLowerCase()
      ).length > 0
    const isPdf =
      (file.type || '').toLowerCase() === 'application/pdf' ||
      file.name.split('.')[file.name.split('.').length - 1] === 'pdf'
    const isLimit =
      file.size / 1024 / 1024 <= (isPdf ? newApplyFileSizeLimit : 20) // pdf格式30M、图片20M
    if (!isJPG && !isPdf) {
      this.$message.error('申请表只能是 JPG/PNG/BMP/JPEG/GIF/PDF 格式。')

      return false
    }
    if (!isLimit) {
      if (isPdf) {
        this.$message.error(
          `PDF格式的申请表大小不能超过${newApplyFileSizeLimit}MB。`
        )
      } else {
        this.$message.error(`图片格式的申请表大小不能超过20MB。`)
      }

      return false
    }
    this.file = Object.assign(
      {},
      { name: file.name, status: 'upload', size: file.size, precent: 0 }
    )
  }

  private beforeUpload(file: any) {
    const isJPG =
      fileTypes.filter(
        (item: string) => item === (file.type || '').toLowerCase()
      ).length > 0
    const isLimit = file.size / 1024 / 1024 <= fileSizeLimit
    if (!isJPG) {
      this.$message.error('申请表只能是 JPG/PNG/BMP/JPEG/GIF 格式。')

      return false
    }
    if (!isLimit) {
      this.$message.error(`申请表大小不能超过${fileSizeLimit}MB。`)

      return false
    }
    this.file = Object.assign(
      {},
      { name: file.name, status: 'upload', size: file.size, precent: 0 }
    )
  }

  // 生成时时申请表图片
  private generateApplyForm(): void {
    if (this.$el) {
      const dom: any = this.$el.querySelector('iframe')

      dom.contentWindow.location.reload()
    }
  }

  private printLoaded(): void {
    const browser = navigator.userAgent.toLowerCase()
    let timer = 0
    this.printLoadedCanvas = ''
    // 兼容IE 显示效果
    if (browser.includes('trident')) timer = 3000

    setTimeout(() => {
      const dom: any = this.$el.querySelector('iframe')

      html2canvas(dom.contentWindow.document.body, {
        useCORS: true,
      }).then(canvas => {
        // 设置预览图片
        if (canvas.width) {
          // this.previewSealImgs = [
          // 	canvas.toDataURL('image/png', 1)
          // ]
          this.printLoadedCanvas = canvas.toDataURL('image/png', 1)
        }

        this.updatePreviewMsg('点击预览')
      })
    }, timer)
  }

  private updatePreviewMsg(msg: string) {
    const { previewForm } = this.$refs as any
    const pEl: any = previewForm.querySelector('p')

    pEl.innerText = msg
  }

  private selectTreeError(obj: any) {
    // 当提示没有选择区域时
    if (obj.code === 4001) {
      // 自动弹起区域选择
      const { areaSelect } = this.$refs as any
      areaSelect.$el.querySelector('input').click()
    }
  }

  private showReference(e: Event): void {
    e.preventDefault()
    e.stopPropagation()
    this.showIndex = 1
    this.exampleVisible = true
    this.isUploadExample = false
    // this.previewSealImgs = [require('../../assets/reference.png')]

    // this.$nextTick(() => {
    //   this.togglePreviewLayer()
    // })
  }

  private closeExample() {
    this.exampleVisible = false
  }

  private nextPage() {
    this.showIndex += 1
  }

  private async confirmExample() {
    this.exampleVisible = false
    if (this.stopShowingExample) {
      await this.ignoreUploadApplyExampleHint({})
      await this.userInfo({})
    }
    if (this.isUploadExample) {
      // 上传
      this.wakeUpload()
    }
  }

  togglePreviewLayer(e?: Event): void {
    if (e) {
      e.stopPropagation()
      if (!this.printLoadedCanvas) return
      this.showPrintBtn = true
      this.previewSealImgs = [this.printLoadedCanvas]
    } else {
      this.showPrintBtn = false
    }

    if (this.previewSealImgs.length) {
      this.$nextTick(() => {
        this.previewImageShow = true
      })
    }
  }

  private stopUploaded(e: Event): void {
    e.stopPropagation()
  }

  private wakeUpload(): void {
    const uploadEl: any = this.$refs.upload

    uploadEl.$el.querySelector('input').click()
  }

  // 调用浏览器打印功能
  private print(): void {
    const ifremaEl: any = this.$refs.printHtml

    ifremaEl.contentWindow.focus()
    ifremaEl.contentWindow.print()
  }

  private uploadConfirm(e: Event): void {
    e.stopPropagation()
    this.showIndex = 1
    this.isUploadExample = true
    if (this.isExampleStopped) {
      this.wakeUpload()
    } else {
      this.exampleVisible = true
    }
  }

  private createApplyForm() {
    ;(this.$refs.sealForm as ElForm).validate((valid: boolean) => {
      if (valid) {
        sessionStorage.setItem(
          'sealInfo',
          JSON.stringify({
            organize: this.sealData.organizeName,
            orgType: formatStatus(orgTypes, this.sealData.organizeType),
            licenseType: formatStatus(
              orgLicenseTypes,
              this.sealData.organizeLicenseType
            ),
            licenseNumber: this.sealData.organizeLicenseNumber,
            agentName: this.sealData.agentName,
            agentLicenseType: formatStatus(
              userLicenseTypes,
              this.sealData.agentLicenseType
            ),
            agentLicenseNumber: this.sealData.agentLicenseNumber,
            agentMobile: this.sealData.agentMobile,
            sealName: this.sealData.sealName,
            useType: formatStatus(useTypes, this.sealData.useType),
            auditOrg: this.sealData.auditOrganizeName,
            isUpdate: this.sealData.licenseNumberSource === 2,
          })
        )
        this.setStateData({ printVisible: true })
      }
    })
  }

  private async selectOrg(val: any) {
    // 用章机构赋值
    // const org: any[] = this.orgList.filter((item: any) => item.organizeUUID === val);
    // if (val) {
    delete this.sealData.licenseNumberFileKey
    this.sealData.licenseNumberSource = 1
    this.sealData = Object.assign(this.sealData, {
      organizeAdministrationLevel: val.administrationLevel,
      organizeLicenseNumber: val.licenseNumber,
      organizeLicenseType: val.licenseType,
      organizeName: val.fullName,
      organizeType: val.organizeType,
      organizeUUID: val.uuid,
    })

    if (val.isSelect) {
      ;(this.$refs['selectTree'] as any) &&
        (this.$refs['selectTree'] as any).setValue(val.fullName || '')
    }
    // if()
    // if () {
    // this.auditOrgs = Object.assign([], this.orgList);
    // this.sealData.auditOrganizeUUID = this.sealData.organizeUUID;
    this.setStateData({
      auditOrgList: [
        {
          auditOrganizeUUID: this.sealData.organizeUUID,
          auditOrganizeLicenseNumber: this.sealData.organizeLicenseNumber,
          auditOrganizeLicenseType: this.sealData.organizeLicenseType,
          auditOrganizeName: this.sealData.organizeName,
        },
      ],
    })
    this.sealData = Object.assign(this.sealData, {
      auditOrganizeUUID:
        this.sealData.sealType !== 1 ? this.sealData.organizeUUID : '',
      auditOrganizeLicenseNumber:
        this.sealData.sealType !== 1 ? this.sealData.organizeLicenseNumber : '',
      auditOrganizeLicenseType:
        this.sealData.sealType !== 1 ? this.sealData.organizeLicenseType : 1,
      auditOrganizeName:
        this.sealData.sealType !== 1 ? this.sealData.organizeName : '',
    })

    await this.queryAuditOrg(this.sealData.organizeUUID)

    this.sealData = Object.assign(this.sealData, {
      auditOrganizeUUID: this.sealData.organizeUUID,
      auditOrganizeLicenseNumber: this.sealData.organizeLicenseNumber,
      auditOrganizeLicenseType: this.sealData.organizeLicenseType,
      auditOrganizeName: this.sealData.organizeName,
    })

    this.$nextTick(() => {
      ;(this.$refs.sealForm as ElForm) &&
        (this.$refs.sealForm as ElForm).clearValidate()
    })
    // }
    // }
  }

  private selectAuditOrg(val: any) {
    const org: any[] = this.orgList
      .concat(this.auditOrgList)
      .filter((item: any) => item.organizeUUID === val)
    if (org && org.length > 0) {
      this.sealData = Object.assign(this.sealData, {
        auditOrganizeLicenseNumber:
          val === this.sealData.organizeUUID
            ? this.sealData.organizeLicenseNumber
            : org[0].organizeLicenseNumber,
        auditOrganizeLicenseType:
          val === this.sealData.organizeUUID
            ? this.sealData.organizeLicenseType
            : org[0].organizeLicenseType,
        auditOrganizeName:
          val === this.sealData.organizeUUID
            ? this.sealData.organizeName
            : org[0].organizeName,
      })
    }
  }

  private setStatus(data: any[], ignore: boolean) {
    data.forEach((item: any) => {
      item.isLeaf = ignore ? true : !item.subFlag
      if (item.subList) {
        this.defaultExpended.push(item.uuid)
        this.setStatus(item.subList, ignore)
      }
    })
  }

  private getAllTree(data: {
    uuid: string
    resolve: any
    text: string
    isFirst: boolean
  }) {
    // 初始化树
    if (!this.area) {
      this.$message.warning('请选择区域')

      return
    }
    this.defaultExpended = []
    this.isShowUpdateOrganization = false
    this.loadTree = !!data.isFirst
    this.getInitTree({
      uuid: data.uuid || this.area,
      fullName: (data.text || '').trim(),
    })
      .then((res: any) => {
        this.isShowUpdateOrganization = !res.length
        this.loadTree = false
        const result = res.map((item: any) => {
          return {
            ...item,
            disabled: !item.selectable,
            isLeaf: !!(data.text || '').trim() ? true : item.subFlag === 0,
          }
        })
        this.setStatus(result, !!(data.text || '').trim())
        data.resolve(result)
      })
      .catch((e: any) => {
        this.loadTree = false
      })
    // }
  }

  private applyLicenseNumberHandler(flag: boolean) {
    if (flag) {
      this.$confirm(
        '您当前选择的组织机构没有对应的统一社会信用代码，需更新社会统一信用代码后再次提交申请',
        '提示',
        {
          confirmButtonText: '前往更新',
          cancelButtonText: '暂不更新',
          type: 'warning',
          closeOnPressEscape: false,
          closeOnClickModal: false,
          customClass: 'custom-confirm',
        }
      )
        .then(() => {
          this.setStateData({
            visible: true,
          })
        })
        .catch(() => {})
    } else {
      this.setStateData({
        visible: true,
      })
    }
  }

  private applyLicenseNumberSubmit(obj: any) {
    if (this.sealData.auditOrganizeUUID === this.sealData.organizeUUID) {
      this.sealData.auditOrganizeLicenseNumber = obj.organizeLicenseNumber
      this.sealData.auditOrganizeLicenseType = obj.organizeLicenseType
    }
    this.ApplyLicenseNumberData = obj
    this.sealData.organizeLicenseType = obj.organizeLicenseType
    this.sealData.organizeLicenseNumber = obj.organizeLicenseNumber
    this.sealData.licenseNumberFileKey = obj.licenseNumberFileKey
    this.sealData.licenseNumberSource = obj.licenseNumberSource

    this.currentOrganizeUUID = this.sealData.organizeUUID
  }

  private handleDialogSelected(v: ICardOption) {
    if (v.title === wrongInfoOptions[0].title) {
      // 机构信息有误
      this.$router.push({
        name: 'organizeUpdate',
        params: {
          type: 'organizationManagement',
        },
        query: {
          orgInfo: `${this.area}-${this.sealData.auditOrganizeUUID}`,
        },
      })
    } else if (v.title === wrongInfoOptions[1].title) {
      // 证照信息有误
      this.applyLicenseNumberHandler(false)
    }
    this.wrongInfoDialogVisible = false
  }

  beforeRouteLeave(to: Route, from: Route, next: any) {
    if (
      !this.errorPage &&
      (to.name !== 'first' || !to.query.login) &&
      to.name !== 'orderConfirm' &&
      (this.active === 0 ||
        this.active === 1 ||
        this.active === 2 ||
        (this.active === 3 && !this.isBackApply)) &&
      this.type === 'newApply'
    ) {
      const content =
        to.name === 'organizationApply'
          ? '创建组织机构需要跳出当前页面操作，是否继续？'
          : '您当前申请的印章还未提交成功，是否确认退出？'
      this.$confirm(content, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnPressEscape: false,
        closeOnClickModal: false,
        customClass: 'custom-confirm',
      })
        .then(() => {
          next()
        })
        .catch(() => {
          next(false)
        })
    } else {
      next()
    }
  }
}
